class CommentsController < ApplicationController
  before_filter [:init_custom_includes, :init_trace_nav]
  before_filter :find_entry
  before_filter :find_comment,
    :only => [:show, :update, :edit, :destroy]
  before_filter :check_login,
    :only => [:new, :edit, :create, :update, :destroy]

  def index
    @comments = @entry.comments
  end

  def show
  end

  def new
    @trace_nav << {:path => entries_url, :label => "Entry Index"} <<
      {:path => entry_url(@entry), :label => "&quot;#{@entry.title}&quot;"}
    @comment = @entry.comments.build
  end
  
  def create
    @comment = @entry.comments.build(params[:comment])
    @comment.content_generator = User.first(
      :conditions => ["username = ?", current_user.username])
    if @comment.save
      flash[:notice] = 'Comment posted'
      redirect_to entry_url(@entry)
    else
      render :action => "new"
    end
  end

  def edit
  end

  def update
    if @comment.update_attributes(params[:comment])
      @comment.content_generator = User.find(:first,
        :conditions => ["username = ?", current_user])
      if @comment.save
        redirect_to entry_comment_url(@entry, @comment)
      else
        render :action => "edit"
      end
    else
      render :action => "edit"
    end
  end

  def destroy
    @comment.destroy
  end

  private
  def check_login
    if current_user
      return true
    else
      deny_permission
    end
  end

  def find_entry
    @entry = Entry.find(params[:entry_id])
  end

  def find_comment
    @comment = Comment.find(params[:id])
  end

  def set_content_generator
    @comment.content_generator = current_user
  end
end
